package com.tabjin.rfidsocket.authority.filter;

import com.tabjin.rfidsocket.common.RequestHolder;
import com.tabjin.rfidsocket.pojo.vo.SysUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tabjin
 * create at 2020/12/22 09:52
 * @program rfid_socket
 * @description
 */
// TODO 在处理/access/*有点不知问题
//@Order(1)
//@WebFilter(filterName = "aLoginFilter", urlPatterns = {"/sys/*", "/admin/*", "/access/*"})
public class ALoginFilter implements Filter {
    // 只有登录到后台的情况下，或者是必须用户登录的情况下才会用到SysUser
    // 因此LoginFilter就是校验用户是否登录的
    // 请求需要用户登录，即取出SysUser来做判断处理，filter就拦截住需要登录的请求
    // 未登录 -> 登录页面
    // 已登录 -> 取出用户信息，然后放入ThreadLocal中，需要登录的接口就会拿到ThreadLocal中的User信息，请求结束的时候再移除掉用户信息

    static final Logger logger = LoggerFactory.getLogger(ALoginFilter.class);

    /**
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter init");
    }

    /**
     * 过滤
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 将ServletRequest转为HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) request;
        // 将ServletResponse转为HttpServletResponse
        HttpServletResponse res = (HttpServletResponse) response;
//        String servletPath = req.getServletPath();// 获取请求的url地址

        // 获取session判断一下
        SysUserVO sysUserVO = (SysUserVO) req.getSession().getAttribute("user");// 这是用户登录成功放入的user
        if (sysUserVO == null) {// 用户未登录
            // TODO 跳转到登录页面
            String path = "/user/login";
            res.sendRedirect(path);
            return;
        }
        // 用户存在
        RequestHolder.add(sysUserVO);
        RequestHolder.add(req);
        String name = RequestHolder.getCurrentUser().getUsername();
        System.out.println("==================" + RequestHolder.getCurrentUser().getUsername());

        // 调用过滤链继续
        chain.doFilter(request, response);
        return;
    }

    @Override
    public void destroy() {

    }
}
